//
//  NewProductDetLineController.m
//  LuCaiZhu
//
//  Created by 邓龙 on 2019/4/25.
//

#import "NewProductDetLineController.h"
#import "HandleNetProduct.h"
#import "myWebViewController.h"
#import "HistoryRoseController.h"
#import "TKAlertCenter.h"
#import "CKPuslichTool.h"
#import "MyAccountCell.h"
#import "WebCell.h"
#import "LineCell.h"
#import "HistoryCell.h"
#import "BaseInfoCell.h"
#import "UIColor+NN.h"
#import "DBHelper.h"
#import "UserModel.h"

@interface NewProductDetLineController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *productTable;
@property (weak, nonatomic) IBOutlet UILabel *productName;
@property (weak, nonatomic) IBOutlet UILabel *expectedRate1;
@property (weak, nonatomic) IBOutlet UILabel *expectedRate2;
@property (weak, nonatomic) IBOutlet UILabel *bottomLab;
@property (weak, nonatomic) IBOutlet UILabel *lab1;
@property (weak, nonatomic) IBOutlet UILabel *lab2;
@property (weak, nonatomic) IBOutlet UILabel *updateTime;
@property (weak, nonatomic) IBOutlet UIView *middleView;
@property (weak, nonatomic) IBOutlet UILabel *middleLab;

@property(nonatomic,strong)NSArray *LineDataArray;
@property (nonatomic, assign) BOOL haveLine;

@property (nonatomic, assign) BOOL topError;
@property (nonatomic, assign) BOOL bottomError;

@property (nonatomic, strong) BaseInfoModel *model;

@end

@implementation NewProductDetLineController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"产品详情";
    
    _productTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _middleLab.hidden = YES;
    _productName.text = _productModel.SubProductName;
    if ([_productModel.SubProductName containsString:@"淡水泉"] || _productModel.Net.length == 0) {
        _lab1.hidden = YES;
        _lab2.hidden = YES;
        _expectedRate1.hidden = YES;
        _expectedRate2.hidden = YES;
        _updateTime.hidden = YES;
    }
    else {
        _expectedRate1.text = _productModel.Net;
        _expectedRate2.text = [NSString stringWithFormat:@"%@%@", _productModel.Rose, @"%"];
    }
    
    _bottomLab.text = _productModel.MatchingDegree;
    if ([_productModel.ProductType isEqualToString:@"C"]) {
        _lab1.hidden = YES;
        _lab2.hidden = YES;
        _expectedRate1.hidden = YES;
        _expectedRate2.hidden = YES;
        _updateTime.hidden = YES;
        _middleLab.hidden = NO;
        NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@万元起", _productModel.SaleAmount]];
        NSRange redRange = NSMakeRange([[contentStr string] rangeOfString:@"万元起"].location, [[contentStr string] rangeOfString:@"万元起"].length);
        [contentStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#efefef"] range:redRange];
        
        [contentStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:redRange];
        [_middleLab setAttributedText:contentStr];
        
        _bottomLab.text = [NSString stringWithFormat:@"可售规模：%@|剩余可售规模：%@%@%@",  _productModel.SumAmount, _productModel.SaleAmountShow, @"\n", _productModel.MatchingDegree];
    }
    
    NSDate *dateTime =  [DBHelper dateFromCustomString:_productModel.DocDate format:@"yyyy/MM/dd HH:mm:ss"];
    NSString *time = [DBHelper stringFromCustomFormatDate:dateTime format:@"yyyy-MM-dd"];
    _updateTime.text = [NSString stringWithFormat:@"更新日期：%@", time?time:_productModel.DocDate];
    
//    if ([_productModel.ProductType isEqualToString:@"D"]) {
//        _bottomLab.text = [NSString stringWithFormat:@"债券型|%@", _productModel.MatchingDegree];
//    }
//    else {
//        _bottomLab.text = [NSString stringWithFormat:@"可售规模|剩余可售规模|%@", _productModel.MatchingDegree];
//    }
    
    if (![_productTypeLevel1 isEqualToString:@"一级市场"] && ![_productModel.ProductType isEqualToString:@"C"]) {
        _bottomLab.textColor = [UIColor colorWithHexString:@"#ffffff"];
        [self getLineDataWithSubId:self.productId];
    }
    
    [self getBaseInfoRequest];
}

- (void)getBaseInfoRequest {
    [HandleNetProduct getBaseInfoById:_productId Success:^(NSDictionary *data) {
        _model = [BaseInfoModel mj_objectWithKeyValues:data];
        [_productTable reloadData];
    } Failure:^(NSString *errorInfo) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 || section == 2 || section == 3) {
        if (section == 0) {
            if (_haveLine) {
                return 2;
            }
            else {
                return 0;
            }
        }
        else if ((section == 2 && _topError) || (section == 2 && _productModel.ProductPath.length==0)) {
            return 0;
        }
        else if (section == 3) {
            if (_model) {
                if ([_productModel.ProductType isEqualToString:@"C"]) {
                    return 9;
                }
                else {
                    return 11;
                }
            }
            else {
                return 0;
            }
        }
        else {
           return 2;
        }
    }
    else if (section == 1) {
        if (_LineDataArray.count == 0) {
            return 0;
        }
        else {
            return _LineDataArray.count<4?_LineDataArray.count+2:6;
        }
    }
    else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1 && _LineDataArray.count > 0) {
        return 50;
    }
    else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    [moreBtn setTitle:@"查看更多" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [moreBtn addTarget:self action:@selector(clickMordAction) forControlEvents:UIControlEventTouchUpInside];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, self.view.frame.size.width-25, 0.5)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#cccccc"];
    [view addSubview:lineView];
    [view addSubview:moreBtn];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 45;
    }
    else {
        if (indexPath.section == 0) {
            return 250;
        }
        else if (indexPath.section == 2 || indexPath.section == 3) {
            if (indexPath.section == 3) {
                if (indexPath.row == 8 && [_productModel.ProductType isEqualToString:@"C"]) {
                    if ([self getStrHeightAction:_model.InvestScope] > 45) {
                        return [self getStrHeightAction:_model.InvestScope]<150?[self getStrHeightAction:_model.InvestScope]+10:[self getStrHeightAction:_model.InvestScope];
                    }
                    else {
                        return 45;
                    }
                }
                else if (indexPath.row == 10 && [_productModel.ProductType isEqualToString:@"D"]) {
                    if ([self getStrHeightAction:_model.InvestScope] > 45) {
                        return [self getStrHeightAction:_model.InvestScope]<150?[self getStrHeightAction:_model.InvestScope]+10:[self getStrHeightAction:_model.InvestScope];
                    }
                    else {
                        return 45;
                    }
                }
                else {
                   return 45;
                }
            }
            else {
                return 300;
            }
        }
        else {
            if (indexPath.row == 1) {
                return 50;
            }
            else {
                return 35;
            }
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MyAccountCell *cell = nil;
        if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"MyAccountCell1"];
        }
        else {
            cell = [tableView dequeueReusableCellWithIdentifier:@"MyAccountCell"];
        }
        if (indexPath.section == 5) {
            cell.separatorInset = UIEdgeInsetsMake(0, self.view.frame.size.width, 0, 0);
        }
        else {
            cell.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0);
        }
        
        switch (indexPath.section) {
            case 0:
                cell.NameLabel.text = @"净值查询";
                break;
            case 1:
                cell.NameLabel.text = @"净值列表";
                break;
            case 2:
                cell.NameLabel.text = @"产品优势";
                break;
            case 3:
                cell.NameLabel.text = @"基本信息";
                break;
            case 4:
                cell.NameLabel.text = @"个人认购提示";
                break;
            case 5:
                cell.NameLabel.text = @"机构认购提示";
                break;
        }
        return cell;
    }
    else {
        if (indexPath.section == 0) {
            LineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LineCell"];
            [cell sortMyData:_LineDataArray];
            return cell;
        }
        else if (indexPath.section == 2 || indexPath.section == 3) {
            if (indexPath.section == 3) {
                BaseInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoCell"];
                [cell setDataAction:_model type:_productModel.ProductType index:indexPath.row];
                return cell;
            }
            else {
                WebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WebCell"];
                if (indexPath.section == 2) {
                    [cell setViewData:_productModel.ProductPath index:indexPath.section];
                }
                else {
                    [cell setViewData:_productModel.BasicPath index:indexPath.section];
                }
                
                cell.returnBlock = ^(NSInteger index) {
                    if (index == 2) {
                        _topError = YES;
                    }
                    else {
                        _bottomError = YES;
                    }
                    [_productTable reloadData];
                };
                return cell;
            }
        }
        else {
            HistoryCell *cell = nil;
            if (indexPath.row == 1) {
                cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryCell"];
            }
            else {
                if (indexPath.row%2 == 0) {
                    cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryCell1"];
                }
                else {
                    cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryCell2"];
                }
                [cell setViewDataAction:_LineDataArray[indexPath.row-2]];
            }
            cell.separatorInset = UIEdgeInsetsMake(0, self.view.frame.size.width, 0, 0);
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 4:
            [self getURLWith:@"Personage"];
            break;
        case 5:
            [self getURLWith:@"InstitutionalSubscription"];
            break;
    }
}

-(void)getURLWith:(NSString *)type{
    NSLog(@"self.productModel.SubProductID==%@",self.productModel.SubProductID);
    NSDictionary *params=@{@"AAAMethodName":type,
                           @"SubProductId":self.productId};
    [HandleNetProduct getDetailForParams:params Success:^(NSDictionary *data) {
        NSString *paths=data[@"Path"];
        
        myWebViewController *vc=(myWebViewController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Setting" viewID:@"myWebViewController"];
        if ([type isEqualToString:@"Personage"]) {
            vc.title=@"个人认购提示";
        }else{
            vc.title=@"机构认购提示";
        }
        vc.urlString=paths;
        
        
        [self.navigationController pushViewController:vc animated:YES];
        
        
    } Failure:^(NSString *errorInfo) {
        
        [[TKAlertCenter defaultCenter]postAlertWithMessage:errorInfo];
        
    }];
    
}

-(void)getLineDataWithSubId:(NSString *)subId{
    NSDictionary *params=@{@"AAAMethodName":@"InfodisclosureNetSelect",@"SubProductId":subId};
    [HandleNetProduct getListforParams:params Success:^(NSArray *data) {
        /**
         DocDate = "2016/7/29 0:00:00";
         IsSelect = No;
         Maximum = "55.34";
         Minimum = "-16.22";
         Net = "1.1512";
         Rose = "-6.71";
         SumNet = "1.1512";
         SumRose = "15.12";
         **/
        if (data.count>0) {
            self.LineDataArray=data;
            _haveLine = YES;
        }else{
            _haveLine = NO;
        }
        [_productTable reloadData];
        
    } Failure:^(NSString *errorInfo) {
        
    }];
}

- (void)clickMordAction {
    HistoryRoseController *vc=(HistoryRoseController *)[CKPuslichTool getViewControllerFromStroyBoard:@"My" viewID:@"HistoryRoseController"];
    vc.dataArray=_LineDataArray;
    [self.navigationController pushViewController:vc animated:YES];
}

- (float)getStrHeightAction:(NSString *)str {
    str = str?str:@"";
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 1;
    UIFont *font = [UIFont systemFontOfSize:13];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-175, CGFLOAT_MAX) options:options context:nil];
    return rect.size.height;
}

@end
